import { defineComponent, PropType, ref, watch } from "vue";

export interface InnerCheckboxProps {
    checked?: any
    disabled?: boolean,
    type?: 'radio' | 'checkbox',
    name?: string,
    label?: any,
    value?: any,
}

export default defineComponent({
    name: 'InnerCheckbox',
    props: {
        disabled: {
            type: Boolean,
        },
        type: {
            type: String as PropType<InnerCheckboxProps['type']>,
        },
        name: {
            type: String as PropType<InnerCheckboxProps['name']>,
        },
        label: {
            type: [String, Object] as PropType<InnerCheckboxProps['label']>,
        },
        checked: {
            type: [String, Boolean] as PropType<InnerCheckboxProps['checked']>,
        },
        value: {
            type: [String, Number] as PropType<InnerCheckboxProps['value']>,
        }
    },
    emits: ['change', 'update:modelValue'],
    setup (props: InnerCheckboxProps, { emit }) {
        const classList = () => ({
            'cm-checkbox': true,
            'cm-checkbox-checked': !!props.checked,
            'cm-checkbox-indeterminate': props.checked === 'indeterminate',
            disabled: props.disabled
        });

        // watch(() => props.checked, () => {
        //     console.log(props.checked);
        //     // checked.value = props.checked;
        // });

        const onClick = (e) => {
            e.preventDefault && e.preventDefault();
            e.stopPropagation && e.stopPropagation();
            if (props.disabled) {
                return;
            }
            if (props.type == 'radio' && props.checked) {
                return;
            }
            let flag = props.checked;
            if (flag === 'indeterminate') {
                flag = true;
            } else {
                flag = !flag;
            }
            emit('change', flag, props.value);
        };

        return () => <div class={classList()} onClick={onClick}>
            {/* 文字对齐辅助 */}
            <span style={{width: '0px', "font-size": '12px', visibility: 'hidden'}}>A</span>
            <input
                type={props.type}
                name={props.name}
                value={props.value}
                style={{display: 'none'}}
                onChange={() => {}}
            />
            <span style={{position: 'relative'}} class="cm-checkbox-outter">
                <span class="cm-checkbox-inner" />
            </span>
            {
                props.label ? <label>{props.label}</label> : null
            }
        </div>;
    }
});
